require "ISBaseObject"

QNW_TS_WeightPool = ISBaseObject:derive("QNW_TS_WeightPool")

local this = QNW_TS_WeightPool

function QNW_TS_WeightPool:add(_value, _weight)
    if not _weight then
        _weight = 10
    end
    table.insert(self.pool, { key = getRandomUUID(), value = _value, weight = _weight })
end

function QNW_TS_WeightPool:random(_count)
    if not _count then
        _count = 1
    end
    _count = math.max(_count, 1)
    _count = math.min(_count, #self.pool)
    local new = {}
    local back = QNW_TS_Util.tableCopy(self.pool)
    for i = 1, _count do
        local random = ZombRand(#back) + 1
        local randomItem = back[random]
        table.insert(new, randomItem.value)
        back = QNW_TS_Util.tableRemoveArray(back, function(_i, _v)
            return _v.key == randomItem.key
        end)
    end
    return new
end

function QNW_TS_WeightPool:randomWeight(_count)
    if not _count then
        _count = 1
    end
    _count = math.max(_count, 1)
    _count = math.min(_count, #self.pool)
    local new = {}
    local back = QNW_TS_Util.tableCopy(self.pool)
    for i = 1, _count do
        local max = 0
        for k, v in pairs(back) do
            max = max + v.weight
        end
        local random = ZombRand(max) + 1
        local randomItem
        for i, v in ipairs(back) do
            random = random - v.weight
            if random <= 0 then
                randomItem = back[i]
                break
            end
        end
        table.insert(new, randomItem.value)
        back = QNW_TS_Util.tableRemoveArray(back, function(_i, _v)
            return _v.key == randomItem.key
        end)
    end
    return new
end

function QNW_TS_WeightPool:new()
    local o = {}
    setmetatable(o, self)
    self.__index = self
    o.pool = {}
    return o
end